package com.lcz.googleplay.config;

import android.graphics.Bitmap;
import android.widget.ImageView;

import com.lcz.googleplay.utils.FileUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.yolanda.nohttp.rest.SimpleResponseListener;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

/**
 * Created by hp on 2016/10/26.
 */

public abstract class BaseProtocol {
    public static final String URL = "http://127.0.0.1:8090/";
    public static final String IMAGE_URL = "http://127.0.0.1:8090/image?name=";


    /**
     * 请求队列。
     */
    private static RequestQueue requestQueue;

    public static void loadImage(String url, SimpleResponseListener<Bitmap> listener) {

        // 创建请求队列, 默认并发3个请求,传入你想要的数字可以改变默认并发数, 例如NoHttp.newRequestQueue(1)。
        requestQueue = NoHttp.newRequestQueue();

        // 创建请求对象。
        Request<Bitmap> imageRequest = NoHttp.createImageRequest(url, RequestMethod.GET, 0, 0, Bitmap.Config.RGB_565, ImageView.ScaleType.CENTER);
        // 添加请求参数。
        requestQueue.add(2, imageRequest, listener);
    }

    public void loadDetailServer(String key, final int index, String packageName) {

        // 创建请求队列, 默认并发3个请求,传入你想要的数字可以改变默认并发数, 例如NoHttp.newRequestQueue(1)。
        requestQueue = NoHttp.newRequestQueue();

        // 创建请求对象。
        final Request<String> request = NoHttp.createStringRequest(URL + key, RequestMethod.GET);
        // 添加请求参数。
        request.add("index", index);
        request.add("packageName", packageName);
        requestQueue.add(1, request, new SimpleResponseListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {
                super.onSucceed(what, response);
                //保存缓存
                saveLocal(response.get(), index);
                System.out.println("BaseProtocol.onSucceed应用详情====" + response.get());
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                super.onFailed(what, response);
            }
        });
    }

    public void loadServer(String key, final int index) {

        // 创建请求队列, 默认并发3个请求,传入你想要的数字可以改变默认并发数, 例如NoHttp.newRequestQueue(1)。
        requestQueue = NoHttp.newRequestQueue();

        // 创建请求对象。
        final Request<String> request = NoHttp.createStringRequest(URL + key, RequestMethod.GET);
        // 添加请求参数。
        request.add("index", index);
        requestQueue.add(1, request, new SimpleResponseListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {
                super.onSucceed(what, response);
                //保存缓存
                saveLocal(response.get(), index);
                System.out.println("BaseProtocol.onSucceed" + response.get());
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                super.onFailed(what, response);
            }
        });
    }

    /**
     * 读取本地缓存
     *
     * @param index
     * @return
     */
    public String loadLocal(int index) {
        //拿到缓存文件
        File dir = FileUtils.getCacheDir();
        File file = new File(dir, getKey() + "_" + index + getParams());
        if (file != null) {
            //读取
            try {
                BufferedReader reader = new BufferedReader(new FileReader(file));
                //先读取缓存的超时时间
                long outOfTime = Long.parseLong(reader.readLine());
                if (outOfTime > System.currentTimeMillis()) {//超时
                    //返回null，重新请求服务器
                    return null;
                } else {
                    String str = null;
                    StringWriter writer = new StringWriter();
                    while ((str = reader.readLine()) != null) {
                        writer.write(str);
                    }

                    return writer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;

            }
        } else {
            return null;
        }
    }

    public String getParams() {
        return "";
    }

    /**
     * 将请求服务器得到的数据保存到本地
     *
     * @param json  服务器得到的数据
     * @param index 服务器请求参数
     */
    public void saveLocal(String json, int index) {
        //拿到缓存文件
        File dir = FileUtils.getCacheDir();

        File file = new File(dir, getKey() + "_" + index + getParams());
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(file));
            //在第一行写上过期时间
            writer.write(System.currentTimeMillis() + 1000 * 10 + "");
            writer.newLine();
            writer.write(json);
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public abstract String getKey();

    public abstract String load(int index);
}
